package br.com.petrobrasrj.session;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import br.com.petrobrasrj.dao.IGenericDao;


@Stateless
public class GenericSession<T> implements IGenericSession<T>{

	private static final long serialVersionUID = 3235565028980347621L;

	@EJB
	protected IGenericDao<T> dao;

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public T save(T t)  {
		validarInsert(t);
		return dao.insert(t);
	}


	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public T update(T t)  {	
		return update(t);
	}
	

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void delete(T t)  {
		validarDelete(t);
		dao.delete(t);
	}
	
	
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public T findById(Class<T> modelClass, Object id){
		return dao.findById(modelClass, id);
	}
	
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public List<T> findAll(Class<T> modelClass){
		return dao.findAll(modelClass);
	}
	
	/**
	 * Validacao antes da insercao
	 * @param t
	 * @throws ValidacaoException
	 */
	protected void validarInsert(T t)  {
		validar(t);
	}

	/**
	 * Validacao antes de um update
	 * @param t
	 * @throws ValidacaoException
	 */
	protected void validarUpdate(T t)  {
		validar(t);
	}

	/**
	 * Validacao antes do delete
	 * @param t
	 * @throws ValidacaoException
	 */
	protected void validarDelete(T t) {}

	/**
	 * Esse metodo deve ser sobrescrito caso haja necessidade de valida????o server-side
	 * @param t
	 * @throws ValidacaoException
	 */
	protected void validar(T t) {}
}
